package com.r2coding.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.r2coding.constant.Constant;
import com.r2coding.entity.UsersEntity;
import com.r2coding.enums.AuthResultEnum;
import com.r2coding.exception.CustomException;
import com.r2coding.mapper.UsersDao;
import com.r2coding.service.UserService;
import com.r2coding.util.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author: 98k灬
 * @since: 2022/11/01
 * @email: 98k_style@sina.com
 * @公众号: 爪哇Guy灬
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UsersDao, UsersEntity> implements UserService {
    @Resource
    AuthenticationManager authenticationManager;

    @Resource
    RedisTemplate redisTemplate;

    /**
     * 登录
     *
     * @param user 用户信息
     * @return JWT
     */
    @Override
    public String login(UsersEntity user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authentication)) {
            throw new CustomException(AuthResultEnum.UNAUTHENTICATED);
        }
        UsersEntity sysUser = (UsersEntity) authentication.getPrincipal();
        String userId = sysUser.getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        // 将用户信息存到redis中
        redisTemplate.opsForValue().set(Constant.LOGIN_KEY + userId, sysUser, Constant.REDIS_EXPIRE_TIME, TimeUnit.HOURS);
        return jwt;
    }



    /**
     * 根据用户名查询用户信息
     *
     * @param name 用户名
     * @return 用户信息
     */
    @Override
    public UsersEntity findByUserName(String name) {
        return this.baseMapper.selectOne(new QueryWrapper<UsersEntity>().eq("username", name));
    }

    /**
     * 根据手机号码查询用户信息
     *
     * @param mobile 手机号码
     * @return 用户信息
     */
    @Override
    public UsersEntity findByMobile(String mobile) {
        return this.baseMapper.selectOne(new QueryWrapper<UsersEntity>().eq("mobile", mobile));
    }
}
